package com.example.administrator.printoutindemo;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.example.administrator.printoutindemo.base.BaseActivity;
import com.example.administrator.printoutindemo.services.Tools;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.utils.ArmsUtils;
import com.xiaoxing.gifloadingview.LoadingDialogUtil;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;

import static com.jess.arms.base.BaseConstants.RESULT_CLOSE;


public class StoreSubmitProject2Activity extends BaseActivity {
    private static final String WEBSERVICE_CONFIG = "TEXT";
    private static final int LOGINSUCCESS = 0;
    private static final int NETWORKERROR = 2;
    private static final int SYSERROR = 3;
    private OutStorageList ol = null;
    private OutStorageListMaterialInfo oli = null;
    private List<OutStorageListMaterialInfo> li_oli = null;
    private StoreSubmitProject2Adapter adapter = null;
    private Button store_sub2_btn_next = null;
    private ListView store_sub2_listView_outStorage = null;
    private TextView s_sub2_act_txt_title = null;
    private EditText s_sub2_act_material = null;
    private CheckBox cbo_isout = null;
    private EditText et_wu_liao_ming_cheng;
    private ImageView img_cha_xun;
    private String SYSException = "";
    private TextView btnRight;
    private String proid;
    private View mEmptyLayout;
    private TextView empty_text;
    private String mLingLiaoLeiXing;
    private String mSearchcondition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.store_activity_submitproject_2);
        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.ling_liao_shen_qing));
        mEmptyLayout = (View) findViewById(R.id.empty);
        empty_text = findViewById(R.id.empty_text);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
        btnRight = (TextView) findViewById(R.id.btnRight);
        btnRight.setText("下一步");
        et_wu_liao_ming_cheng = (EditText) findViewById(R.id.et_wu_liao_ming_cheng);
        img_cha_xun = (ImageView) findViewById(R.id.img_cha_xun);
        img_cha_xun.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                getOutStorageListInfo(proid, TextUtils.isEmpty(et_wu_liao_ming_cheng.getText().toString().trim()) ? "" : et_wu_liao_ming_cheng.getText().toString().trim());


            }
        });
        adapter = new StoreSubmitProject2Adapter(this);

        ol = (OutStorageList) getIntent().getSerializableExtra("outStorageList");
        mLingLiaoLeiXing = getIntent().getExtras().getString("ling_liao_lei_xing");
        mSearchcondition = getIntent().getExtras().getString("searchcondition");

        oli = new OutStorageListMaterialInfo(this);


        store_sub2_btn_next = (Button) findViewById(R.id.store_sub2_btn_next);
        store_sub2_listView_outStorage = (ListView) findViewById(R.id.store_sub2_listView_outStorage);
        s_sub2_act_txt_title = (TextView) findViewById(R.id.s_sub2_act_txt_title);
        cbo_isout = (CheckBox) findViewById(R.id.cbo_isout);
        // s_sub2_act_material =
        // (EditText)findViewById(R.id.s_sub2_act_material);//物料描述文本框，用于查询条件

        btnRight.setOnClickListener(new store_sub2_btn_next_click());


        if (null != ol) {

            s_sub2_act_txt_title.setText("出库单号：" + ol.get_out_storagelist_batchid());

            proid = ol.get_proid();

            getOutStorageListInfo(proid, "");


        } else {
            Tools.showDialogInfo(this, store_sub2_btn_next, "登录已过期，请重新填写出库申请");
        }
    }

    private void getOutStorageListInfo(String proid, String material) {

        LoadingDialogUtil.showGifdialog2(getSupportFragmentManager(), R.drawable.public_loading);
        String methodName = "GetOutStorageListInfo";
        SoapParams params = new SoapParams();

        if (mLingLiaoLeiXing.equals("2")) { //如果是1为普通领料，2位电表领料
            methodName = "GetOutStorageMeterListInfo";
            params.put("proid", proid);
            params.put("searchcondition", mSearchcondition);
        } else {
            methodName = "GetOutStorageListInfo";
            params.put("proid", proid);
            params.put("materail", material);
        }


        /**
         * 请求
         */
        String finalMethodName = methodName;
        soapUtil.callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                LoadingDialogUtil.dismissDialog();

                String result = object.getProperty(finalMethodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    if (li_oli != null) li_oli.clear();
                    li_oli = oli.getListFromJSON(result);
                    adapter.setList(li_oli);
                    store_sub2_listView_outStorage.setAdapter(adapter);
                    mEmptyLayout.setVisibility(View.GONE);
                    store_sub2_listView_outStorage.setVisibility(View.VISIBLE);
                } else {
                    mEmptyLayout.setVisibility(View.VISIBLE);
                    store_sub2_listView_outStorage.setVisibility(View.GONE);
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                LoadingDialogUtil.dismissDialog();
                ArmsUtils.makeText(getContext(), error.getMessage());

            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                LoadingDialogUtil.dismissDialog();

            }
        }, getAapiUserName(), getApiPwd());

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_CLOSE) {
            setResult(RESULT_CLOSE);
            finish();
        }
    }

    public String getRandomWords() {
        String resultStr = "";
        String s = "abcdefghijklmnopqrstuvwxyz";
        char[] c = s.toCharArray();
        Random random = new Random();
        for (int i = 0; i < 3; i++) {

            resultStr += c[random.nextInt(c.length)];
        }

        return resultStr;
    }

    public String getRandomWordsForPass() {
        String resultStr = "";
        String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        char[] c = s.toCharArray();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            resultStr += c[random.nextInt(c.length)];
        }

        return resultStr;
    }

    private class store_sub2_btn_next_click implements OnClickListener {
        @Override
        public void onClick(View v) {

            List<Map<String, String>> li = adapter.getListSelected();
            List<OutStorageList> osll = new ArrayList<OutStorageList>();

            boolean flag = true;

            SimpleDateFormat df = new SimpleDateFormat("HHmmss");//设置日期格式
            String timestr = df.format(new Date());
            String receive_loginName = getRandomWords() + timestr;//生成随机开门用户名
            String receive_loginPwd = getRandomWordsForPass();//随机开门密码

            for (Map<String, String> map : li) {
                // System.out.println("the mid of "+map.get("list_item_mid")
                // +" EditText：----------->"+map.get("list_item_inputvalue")
                // +" surplus:---->"+map.get("list_item_surplus"));

                String value = map.get("list_item_inputvalue");// 出库数量
                String surplus = map.get("list_item_surplus");// 剩余数量

                if (!"".equals(value) && !"0".equals(value)) {

                    BigDecimal outCount = new BigDecimal(value);
                    // 设置小数位数，第一个变量是小数位数，第二个变量是取舍方法(四舍五入)
                    outCount = outCount.setScale(4, BigDecimal.ROUND_HALF_UP);

                    BigDecimal surplusCount = new BigDecimal(surplus);
                    surplusCount = surplusCount.setScale(4,
                            BigDecimal.ROUND_HALF_UP);

                    // 出库数量大于剩余数量
                    if (outCount.compareTo(surplusCount) == 1) {
                        flag = false;
                    }

                }


            }

            if (flag) {
                for (Map<String, String> map : li) {

                    String value = map.get("list_item_inputvalue");// 出库数量
                    String mid = map.get("list_item_mid");
                    String materialCode = map.get("list_item_materialCode");
                    String unit = map.get("list_item_unit");
                    String materialInfo = map.get("list_item_title");

                    if (!"".equals(value) && !"0".equals(value)) {

                        OutStorageList osl = new OutStorageList();

                        osl.set_check_status("未审核");
                        osl.set_deal_status("未处理");
                        osl.setShenQingRen(ol.getShenQingRen());
                        osl.setMaterialCode(materialCode);
                        osl.setUnit(unit);
                        osl.set_check_user_id(ol.get_check_user_id());
                        osl.set_check_user_name(ol.get_check_user_name());
                        osl.set_target_project(ol.get_target_project());
                        osl.set_out_storage_estimate(ol
                                .get_out_storage_estimate());
                        osl.set_receive_address(ol.get_receive_address());
                        osl.set_receive_username(ol.get_receive_username());
                        osl.set_receive_userphone(ol.get_receive_userphone());
                        osl.set_material_user_id(ol.get_material_user_id());
                        osl.set_out_storagelist_batchid(ol
                                .get_out_storagelist_batchid());
                        osl.set_proid(ol.get_proid());
                        osl.set_projectName(ol.get_projectName());
                        osl.set_proid(ol.get_proid());

                        osl.set_material_id(Integer.parseInt(mid));
                        osl.set_materialInfo(materialInfo);
                        osl.set_out_storage_count(value);


                        //是否添加自动扫码出库人员
                        if (cbo_isout.isChecked()) {
                            osl.set_receive_loginName(receive_loginName);
                            osl.set_receive_loginPwd(receive_loginPwd);
                            osl.set_receive_loginTrueName("扫码出库");
                        }

                        osll.add(osl);
                    }
                }

                Intent in = new Intent();
                Bundle bunl = new Bundle();
                bunl.putSerializable("outStorageListInfo", (Serializable) osll);
                in.putExtras(bunl);
                in.setClass(StoreSubmitProject2Activity.this, StoreSubmitProject3Activity.class);
                startActivityForResult(in, RESULT_CLOSE);


            } else {
                Tools.showDialogInfo(StoreSubmitProject2Activity.this,
                        store_sub2_btn_next, "出库数量有大于剩余数量的物料！请调整数量。");
            }

        }
    }
}